package com.baomidou.springmvc.common.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URLDecoder;
 

@SuppressWarnings("deprecation")
public class HttpRequestUtils {
    private static Logger log = Logger.getLogger(HttpRequestUtils.class);    //日志记录
 
    /**
     * httpPost
     * @param url  路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam){
        return httpPost(url, jsonParam, false);
    }
 
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        //post请求返回结果
        @SuppressWarnings({ "resource" })
		DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.fromObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }
 
 
    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpGet(String url){
    	if(url.indexOf("|") >= 0){
    		url = url.replace("|", "%7C");
    	}
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            @SuppressWarnings({ "resource" })
			DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
               
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                log.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            log.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }
    
    /**
     * 
     * @description 根据地址获取该地址的经纬度
     * @author hewei
     * @title: getLngAndLat
     * @date 2017年5月11日 下午2:45:44
     * @param addr
     * @return String
     */
    public static String getLngAndLat(String addr){
    	try{
    		String url = "";
    		url = String.format("http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=ouLLx3nWFz1zrQNt66KrQ7NMmOA6XSMo", addr);
    		JsonParser parser = new JsonParser(); 
    	    // 使用解析器解析json数据，返回值是JsonElement，强制转化为其子类JsonObject类型
    	    JsonObject object = (JsonObject) parser.parse(httpGet(url).toString());
        	object = (JsonObject) parser.parse(object.get("result").toString());
        	object = (JsonObject) parser.parse(object.get("location").toString());
        	return object.get("lng").toString()+";"+object.get("lat");
    	}catch(Exception e){
    		log.error("==============获取经纬度时发生错误");
    		return "error";
    	}
		
    }
    
    /**
     * 
     * @description 实现百度地图输入关键字自动提示出相关地点
     * @author hewei
     * @title: placeSuggestion
     * @date 2017年5月11日 下午3:00:33
     * @param query
     * @param region
     * @return JSONObject
     */
    
    public static JSONObject placeSuggestion(String query,String region){
    	String url = "";
    	url = String.format("http://api.map.baidu.com/place/v2/suggestion?query=%s&region=%s&city_limit=false&output=json&ak=ouLLx3nWFz1zrQNt66KrQ7NMmOA6XSMo", query,region);
    	log.info("url==========="+url);
    	return httpGet(url);
    }
    /**
     * 
     * @description 根据两个坐标获取两点之间的距离
     * @author hewei
     * @title: getDriverDistance
     * @date 2017年5月11日 下午6:15:06
     * @param pom1
     * @param pom2
     * @return String
     */
    public static String getDriverDistance(String pom1,String pom2){
    	String url = "";
    	url = String.format("http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=%s&destinations=%s&ak=ouLLx3nWFz1zrQNt66KrQ7NMmOA6XSMo&tactics=11", pom1, pom2);
    	log.info("=================="+url);
    	JsonParser parser = new JsonParser(); 
	    // 使用解析器解析json数据，返回值是JsonElement，强制转化为其子类JsonObject类型
	    JsonObject object = (JsonObject) parser.parse(httpGet(url).toString());
	    return object.toString();
    }
  
    /**
     * 读用户基本消息 user节点
     *
     * @param reader JsonReader
     */
    public static String GetImageStr()  
	{//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
		String imgFile = "d://test.jpg";//待处理的图片  
		InputStream in = null;  
		byte[] data = null;  
		//读取图片字节数组  
		try   
		{  
			in = new FileInputStream(imgFile);          
			data = new byte[in.available()];  
			in.read(data);  
			in.close();  
		}   
		catch (IOException e)   
		{  
			e.printStackTrace();  
		}  
		//对字节数组Base64编码  
		BASE64Encoder encoder = new BASE64Encoder();  
		return encoder.encode(data);//返回Base64编码过的字节数组字符串  



	}
	
    
    public static void main(String[] args) throws IOException { 

    	getLngAndLat("108智库空间");

	}
}


